%%%-------------------------------------------------------------------
%%% @author Rain
%%% @doc 网页操作相关接口
%%% 接口目前均基于cowboy,若要使用请将cowboy引入为dep
%%% @end
%%%-------------------------------------------------------------------
-module(game_util_web).
-author("Rain").
-include("game_util_web.hrl").

%% API
-export([set_cors_header/1]).
-export([post/3, post/4]).
-export([get/1, get/2]).
-export([request_body/1, request_body/2]).
-export([reply_success_json/3]).

%% @doc 发起post请求
post(Url, Type, Data) ->
    post(Url, Type, Data, ?DEFAULT_HTTP_TIMEOUT).
post(Url, Type, Data, Timeout) ->
    HttpOpts = [{timeout, Timeout}],
    Opts = [{sync, true}, {body_format, binary}, {full_result, false}],
    httpc:request(post, {Url, [], Type, iolist_to_binary(Data)}, HttpOpts, Opts).

%% 获取请求内的数据
request_body(Req) ->
    request_body(Req, []).
request_body(Req, Opts) ->
    request_body(Req, Opts, <<>>).
request_body(Req, Opts, Acc) ->
    case cowboy_req:read_body(Req, opts_body_opts(Opts)) of
        {ok, Data, NewReq} ->
            {NewReq, <<Acc/binary, Data/binary>>};
        {more, Data, NewReq} ->
            request_body(NewReq, Opts, <<Acc/binary, Data/binary>>)
    end.

opts_body_opts(Opts) -> proplists:get_value(body_opts, Opts, #{}).

%% @doc 发起get请求
get(Url) ->
    get(Url, ?DEFAULT_HTTP_TIMEOUT).
get(Url, Timeout) ->
    HttpOpts = [{timeout, Timeout}],
    Opts = [{sync, true}, {body_format, binary}, {full_result, false}],
    httpc:request(get, {Url, []}, HttpOpts, Opts).


%% @doc 设置CORS的Header
set_cors_header(Req) ->
    Req1 = cowboy_req:set_resp_header(?HTTP_OPTION_ACCESS_CONTROL_ALLOW_ORIGIN, <<"*">>, Req),
    Req2 = cowboy_req:set_resp_header(?HTTP_OPTION_ACCESS_CONTROL_ALLOW_METHODS, <<"POST, GET, PUT, OPTIONS, DELETE">>, Req1),
    Req3 = cowboy_req:set_resp_header(?HTTP_OPTION_ACCESS_CONTROL_ALLOW_HEADERS, <<"content-type">>, Req2),
    Req3.

%% @doc 回复200成功
%% EJson: #{}
reply_success_json(EJson, Req, State) ->
    {ok, JsonData} = game_util:json_encode(EJson),
    Headers = #{?HTTP_OPTION_CONTENT_TYPE => ?HTTP_CONTENT_TYPE_JSON},
    RetReq = cowboy_req:reply(200, Headers, JsonData, Req),
    {ok, RetReq, State}.
